/*
 * @lc app=leetcode.cn id=98 lang=cpp
 *
 * [98] 验证二叉搜索树
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isFirst = true;
    int lastValue = INT_MIN;

    bool isValidBST(TreeNode* root) {
        return dfs(root);
    }

    // 中序遍历
    bool dfs(TreeNode* root) {
        // 递归终止条件
        if (root == nullptr) return true;
        
        // 左子树
        if(dfs(root->left) == false) return false;

        // 当前节点
        if (isFirst) {
            lastValue = root->val;
            isFirst = false;
        } else {
            if (root->val <= lastValue) {
                return false;
            } else {
                lastValue = root->val;
            }
        }

        // 右子树
        if(dfs(root->right) == false) return false;

        return true;
    }
};
// @lc code=end

